﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.GData.Client;
using System.Text.RegularExpressions;

namespace Dropit.BlogPageProvider.Blogger
{
	public class Utility
	{
		#region Fields

		private static Regex BlogIDRegex = new System.Text.RegularExpressions.Regex("blog-([0-9]*)", RegexOptions.Compiled);
		private static Regex PostIDRegex = new System.Text.RegularExpressions.Regex("post-([0-9]*)", RegexOptions.Compiled);
		private static Regex CommentIDRegex = new System.Text.RegularExpressions.Regex("comment-([0-9]*)", RegexOptions.Compiled);

		#endregion

		#region Static Parse Methods

		public static string ExtractBlogId(AtomUri uri)
		{
			System.Text.RegularExpressions.Match match = BlogIDRegex.Match(uri.ToString());
			if (match != null && match.Groups.Count == 2)
			{
				return match.Groups[1].Value;
			}
			return null;
		}

		public static string ExtractPostId(AtomUri uri)
		{
			System.Text.RegularExpressions.Match match = PostIDRegex.Match(uri.ToString());
			if (match != null && match.Groups.Count == 2)
			{
				return match.Groups[1].Value;
			}
			return null;
		}

		public static string ExtractCommentId(AtomUri uri)
		{
			System.Text.RegularExpressions.Match match = CommentIDRegex.Match(uri.ToString());
			if (match != null && match.Groups.Count == 2)
			{
				return match.Groups[1].Value;
			}
			return null;
		}

		#endregion

		public static List<AtomEntry> GetFeedEntries(Service service, string feedUrl)
		{
			if (!string.IsNullOrEmpty(feedUrl))
			{
				AtomFeed feed = service.Query(new FeedQuery(feedUrl));
				return feed.Entries.ToList<AtomEntry>();
			}
			return new List<AtomEntry>(0);
		}

		public static Service CreateService(BlogPageProvider.Blog.Connection connection)
		{
			Service service = new Service("blogger", "dropit-pageprovider-1");
			service.Credentials = new GDataCredentials(connection.Username, connection.Password);
			GDataGAuthRequestFactory factory = (GDataGAuthRequestFactory)service.RequestFactory;
			factory.AccountType = "GOOGLE";
			return service;
		}
	}
}
